package com.example.blog.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.entity.LoginFormDTO;
import com.example.blog.entity.Result;
import com.example.blog.entity.User;
import com.example.blog.entity.UserStatus;
import com.example.blog.mapper.UserMapper;
import com.example.blog.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.lang.UUID;

import static com.example.blog.utils.RedisConstants.LOGIN_TOKEN_TTL;
import static com.example.blog.utils.RedisConstants.LOGIN_USER_KEY;
import com.example.blog.utils.PasswordEncoder;
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Result login(LoginFormDTO loginForm, HttpSession session) {
        final String userName = loginForm.getUserName();
        final String userPwd = loginForm.getUserPwd();
        if(userPwd == null || userPwd.isEmpty() || userName == null || userName.isEmpty()){
            return Result.fail("账号或密码不能为空");
        }
        User user = query().eq("user_name", userName).one();
        if(user == null || !PasswordEncoder.matches(user.getUserPwd(), userPwd)){
            return Result.fail("账号或密码错误");
        }

        if(user.getUserStatus() == UserStatus.FORBID){
            return Result.fail("该账号被封禁");
        }
        final String token = UUID.randomUUID().toString(true);

        final Map<String, Object> userMap = new HashMap<>();
        final Field[] fields = user.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if(field.getName().equals("userPwd")) {
                continue;
            }
            try {
                Object value = field.get(user);
                if(value == null) {
                    value = "";
                }
                userMap.put(field.getName(), value.toString());
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        String loginUser = LOGIN_USER_KEY + user.getUserId();

        // 获取上一个token如果有则删除
        final String oldToken = stringRedisTemplate.opsForValue().get(loginUser);

        if(oldToken != null){
            stringRedisTemplate.delete(oldToken);
        }

        // 将数据放入新的token
        final String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        stringRedisTemplate.opsForValue().set(loginUser, tokenKey);

        // 设置有效期
        stringRedisTemplate.expire(loginUser, LOGIN_TOKEN_TTL + 1, TimeUnit.DAYS);
        stringRedisTemplate.expire(tokenKey, LOGIN_TOKEN_TTL, TimeUnit.DAYS);
        return Result.ok(token);
    }

    public Result getUser() {
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("userNickname", UserHolder.getUser().getUserNickname());
        userMsg.put("userImg", UserHolder.getUser().getUserImg());
        userMsg.put("userInfo", UserHolder.getUser().getUserInfo());
        return Result.ok(userMsg);
    }


}
